<?php

namespace app\shop\controller\Order;

use think\Controller;

class Order extends Controller
{
    // 订单模型
    protected $OrderModel = null;

    // 订单商品模型
    protected $OrderProductModel = null;

    // 购物车模型
    protected $CartModel = null;
    protected $BusinessModel = null;
    protected $ProductModel = null;
    protected $RecordModel = null;


    public function __construct()
    {
        parent::__construct();

        // 加载模型
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
        $this->ProductModel = model('Product.Product');
        $this->CartModel = model('Order.Cart');
    }

    public function index()
    {
        $busid = $this->request->param('busid', 0, 'trim');

        $status = $this->request->param('status', '', 'trim');

        $orderId = $this->request->param('orderId', 0, 'trim');


        if ($orderId) {
            $this->OrderModel->isUpdate(true)->save(['status' => 3], ['id' => $orderId]);
        }

        $where = [
            'busid' => $busid
        ];

        if ($status !== '') {
            $where['status'] = $status;
        }

        $OrderList = $this->OrderModel->where($where)->order('createtime', 'desc')->select();

        foreach ($OrderList as &$item) {
            $OrderProductData = $this->OrderProductModel->with(['products'])->where(['orderid' => $item['id']])->select();
            // halt($this->OrderProductModel->getLastSql());
            $item['OrderProduct'] = $OrderProductData;
        }

        $this->success('查询成功', null, $OrderList);

        /* 
            订单数据
            商品数据
        */
        // [
        //     订单数据
        //     [
        //         订单商品数据
        //         [
        //             商品数据
        //         ]
        //     ]
        // ]
    }

    public function delete()
    {
        $orderid = $this->request->param('orderid', 0, 'trim');

        $order = $this->OrderModel->find($orderid);

        if (!$order) {
            $this->error('订单不存在');
        }

        $result = $this->OrderModel->where('id', $orderid)->delete();

        if ($result) {
            $this->success('删除订单成功');
        }
    }

    public function info()
    {
        $orderid = $this->request->param('orderid', 0, 'trim');

        $order = $this->OrderModel->find($orderid);

        if (!$order) {
            $this->error('订单不存在');
        }

        $Address = model('Business.Address')->find($order['businessaddrid']);

        $OrderProductData = $this->OrderProductModel->with(['products'])->where(['orderid' => $orderid])->select();

        $data = [
            'order' => $order,
            'address' => $Address,
            'product' => $OrderProductData
        ];

        $this->success('查询成功', null, $data);
    }

    public function express()
    {
        // error_reporting(E_ALL || ~E_NOTICE);
        // $host = "https://wuliu.market.alicloudapi.com"; //api访问链接
        // $path = "/kdi"; //API访问后缀
        // $method = "GET";
        // $appcode = "0a3ec4b02bf04395b184445136241ab1"; //开通服务后 买家中心-查看AppCode
        // $headers = array();
        // array_push($headers, "Authorization:APPCODE " . $appcode);
        // $querys = "no=780098068058&type=zto";  //参数写在这里
        // $bodys = "";
        // $url = $host . $path . "?" . $querys;

        // $curl = curl_init();
        // curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        // curl_setopt($curl, CURLOPT_URL, $url);
        // curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($curl, CURLOPT_FAILONERROR, false);
        // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($curl, CURLOPT_HEADER, true);
        // if (1 == strpos("$" . $host, "https://")) {
        //     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        //     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        // }
        // $out_put = curl_exec($curl);

        // $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        // if ($httpCode == 200) {
        //     print($body);
        // } else {
        //     if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
        //         print("参数错误");
        //     } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
        //         print("AppCode错误");
        //     } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
        //         print("请求的 Method、Path 或者环境错误");
        //     } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
        //         print("服务未被授权（或URL和Path不正确）");
        //     } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
        //         print("套餐包次数用完");
        //     } elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
        //         print("套餐包次数用完，请续购套餐");
        //     } elseif ($httpCode == 500) {
        //         print("API网关错误");
        //     } elseif ($httpCode == 0) {
        //         print("URL错误");
        //     } else {
        //         print("参数名错误 或 其他错误");
        //         print($httpCode);
        //         $headers = explode("\r\n", $header);
        //         $headList = array();
        //         foreach ($headers as $head) {
        //             $value = explode(':', $head);
        //             $headList[$value[0]] = $value[1];
        //         }
        //         print($headList['x-ca-error-message']);
        //     }
        // }
    }

    public function submit()
    {
        // 如果前台从购物车页面进入，就获取到传入的购物车列表id
        $cartids = $this->request->param('cartids', '', 'trim');

        // 如果前台从商品详情页面进入，就获取到传入的商品id
        $proid = $this->request->param('proid', '', 'trim');

        $addrid = $this->request->param('addrid', 0, 'trim');

        $busid = $this->request->param('busid', 0, 'trim');

        $content = $this->request->param('content', '', 'trim');

        if ($cartids) {
            $CartList = $this->CartModel->with(['product'])->whereIn('cart.id', $cartids)->select();

            if (!$CartList) {
                $this->error('请选择结算的商品');
            }
        }

        if ($proid) {
            $CartList = $this->ProductModel->where('id', $proid)->select();
        }

        $Business = $this->BusinessModel->find($busid);

        if (!$Business) {
            $this->error('用户不存在');
        }

        $Address = model('Business.Address')->find($addrid);

        if (!$Address) {
            $this->error('收货地址不存在');
        }

        // 这个订单的总金额
        $total = 0;

        foreach ($CartList as $item) {
            // 判断购物车的每件商品库存是否够用户购买
            if ($item['pronum'] > $item['product']['stock']) {
                $this->error($item['product']['name'] . '的库存不足');
            }

            $total += $item['total'];
        }

        // 判断用户余额是否足够下单
        if ($Business['money'] < $total) {
            $this->error('余额不足');
        }

        /* 
            order => 新增订单
            order_product => 新增订单关联商品数据

            product => 需要更新商品库存
            business => 更新用户的余额
            business_record => 新增该用户消费记录

            order_cart => 下单成功后需要把已下单的购物车商品删除

            事务操作
        */

        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();
        $this->ProductModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();
        $this->CartModel->startTrans();

        // 封装订单数据
        $OrderData = [
            'code' => build_code('BU'),
            'busid' => $busid,
            'businessaddrid' => $addrid,
            'amount' => $total,
            'remark' => $content,
            'status' => 2
        ];

        // 插入数据库
        $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

        if ($OrderStatus === FALSE) {
            $this->error($this->OrderModel->getError());
        }


        // 封装订单商品数据
        $OrderProductData = [];

        foreach ($CartList as $item) {
            $OrderProductData[] = [
                'orderid' => $this->OrderModel->id,
                'proid' => $item['proid'],
                'pronum' => $item['pronum'],
                'price' => $item['price'],
                'total' => $item['total']
            ];
        }

        // 实例化验证器
        $OrderProductValidate = validate('common/Order/Product');

        foreach ($OrderProductData as $item) {
            if ($OrderProductValidate->check($item) === FALSE) {
                $this->error($OrderProductValidate->getError());
            }
        }

        // 批量插入数据库
        $OrderProductStatus = $this->OrderProductModel->saveAll($OrderProductData);

        if ($OrderProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->error('新增订单商品记录失败');
        }

        // 封装商品数据
        $ProductData = [];

        foreach ($CartList as $item) {
            $ProductData[] = [
                'id' => $item['proid'],
                'stock' => bcsub($item['product']['stock'], $item['pronum'])
            ];
        }

        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if ($ProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error('更新库存失败');
        }

        // 封装用户的余额
        $BusinessData = [
            'id' => $busid,
            'money' => bcsub($Business['money'], $total, 2)
        ];

        $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->error('更新用户余额失败');
        }

        // 消费记录
        $RecordData = [
            'total' => $total,
            'busid' => $busid,
            'content' => "您的订单{$OrderData['code']}消费了{$total}元",
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);

        if ($RecordStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        $CartStatus = $this->CartModel->where('id', 'in', $cartids)->delete();

        if ($CartStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->error('删除购物车记录失败');
        }

        if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE || $CartStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->ProductModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->CartModel->rollback();
            $this->error('下单失败');
        } else {
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->ProductModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->CartModel->commit();
            $this->success('下单成功');
        }
    }

    public function rate()
    {
        $busid = $this->request->param('busid', 0, 'trim');
        $orderid = $this->request->param('orderid', 0, 'trim');
        $data = $this->request->param('data', '', 'trim');

        // 接收字符串转成数组
        $Ratedata = json_decode($data, true);

        $order = $this->OrderModel->find($orderid);

        if (!$order) {
            $this->error('订单不存在');
        }

        if ($data) {
            $ProductData = [];

            foreach ($Ratedata as $item) {
                // 只处理上传
                if (isset($item['proid']) && !empty($item['proid'])) {
                    $result = build_uploads($item['proid']);

                    if ($result['code'] === 0) {
                        $this->error($result['msg']);
                    }
                }

                $ProductData[] = [
                    'id' => $item['id'],
                    'rate' => $item['rate'],
                    'comment' => $item['comment'],
                    'photos' => !empty($result['data']) ? implode(',', $result['data']) : ''
                ];
            }
        }
        /* 
            订单商品表 => 更新评价，评分，图集
            订单表 => 更新订单状态
        */

        // 开启事务
        $this->OrderModel->startTrans();
        $this->OrderProductModel->startTrans();

        // 组装订单数据
        $OrderData = [
            'id' => $orderid,
            'status' => 4,
        ];

        $OrderStatus = $this->OrderModel->isUpdate(true)->save($OrderData);

        if ($OrderStatus === FALSE) {
            $this->error('更新订单状态失败');
        }

        // 更新订单商品表
        $OrderProductStatus = $this->OrderProductModel->isUpdate(true)->saveAll($ProductData);

        if ($OrderProductStatus === FALSE) {
            $this->OrderModel->rollback();
            $this->error('更新订单商品失败');
        }

        if ($OrderProductStatus === FALSE || $OrderStatus === FALSE) {
            foreach ($ProductData as $item) {
                if (!empty($item['photos'])) {
                    $photoArr = explode(',', $item['photos']);

                    $photoArr = array_filter($photoArr);

                    foreach ($photoArr as $item) {
                        @is_file('.' . $item) && @unlink('.' . $item);
                    }
                }
            }

            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->error('评价失败');
        } else {
            $this->OrderModel->commit();
            $this->OrderProductModel->commit();
            $this->success('评价成功');
        }
    }
}
